package com.yoke.assistant.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.Toast;

import com.orhanobut.logger.Logger;

import java.util.List;

public class AppUtil {

    public static Context sContext;

    public static void showToast(String text){
        Toast.makeText(sContext, text, Toast.LENGTH_LONG).show();
    }

    public static Intent getAppOpenIntentByPackageName(String packageName) {
        PackageManager pkgMag = sContext.getPackageManager();

        PackageInfo packageInfo = null;
        try {
            packageInfo = pkgMag.getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            Logger.e("find package", e);
        }
        if (packageInfo == null) {
            Logger.w("no package info");
            return null;
        }

        return getLauncherIntent(packageName, pkgMag);
    }

    public static Intent getLauncherIntent(String packageName, PackageManager pkgMag) {
        String mainAct = null;
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);

        List<ResolveInfo> list = pkgMag.queryIntentActivities(intent,
                PackageManager.GET_ACTIVITIES);
        for (int i = 0; i < list.size(); i++) {
            ResolveInfo info = list.get(i);
            if (info.activityInfo.packageName.equals(packageName)) {
                mainAct = info.activityInfo.name;
                break;
            }
            if (info.loadLabel(pkgMag).toString().contains(packageName)) {
                mainAct = info.activityInfo.name;
                packageName = info.activityInfo.packageName;
                break;
            }
        }
        if (TextUtils.isEmpty(mainAct)) {
            Logger.w("no package");
            return null;
        }
        intent.setComponent(new ComponentName(packageName, mainAct));
        return intent;
    }

}
